#include "json.h"

ipconfig read_client_config(const char *filename){
    ipconfig config = {"127.0.0.1","8989"};

    FILE*fp = fopen(filename,"r");
    if(fp){
        fseek(fp,0,SEEK_END);
        long length = ftell(fp);
        fseek(fp,0,SEEK_SET);
        char*data = (char*)malloc(length+1);
        fread(data,1,length,fp);
        data[length] = '\0';
        fclose(fp);


        cJSON*json = cJSON_Parse(data);
        if(json){
            cJSON*client = cJSON_GetObjectItemCaseSensitive(json,"client");
            if(client){
                cJSON*ip = cJSON_GetObjectItemCaseSensitive(client,"ip");
                cJSON*port = cJSON_GetObjectItemCaseSensitive(client,"port");

                if(cJSON_IsString(ip)&&(ip->valuestring != NULL)){
                    strncpy(config.ip,ip->valuestring,sizeof(config.ip)-1);
                }
                if(cJSON_IsString(port)&&(port->valuestring != NULL)){
                    strncpy(config.port,port->valuestring,sizeof(config.port)-1);
                }
            }
            cJSON_Delete(json);
        }
        free(data);
    }
    return config;
}

